//
//  CLOProgressView.swift
//  CLOCamera_Example
//
//  Created by Clover on 2018/5/17.
//  Copyright © 2018年 CocoaPods. All rights reserved.
//

import UIKit

class CLOProgressView: UIView {
    /// 进度条
    var progressValue: CGFloat = 0
    /// 当前时间
    var currentTime: CGFloat = 0
    
    var timer: Timer?
    
    private var  _maxTime: CGFloat = 0
    var maxTime: Int{
        set{
            _maxTime = CGFloat(newValue)
            currentTime = 0
            progressValue = 0
            self.isHidden = false
            self.perform(#selector(starProgress), with: nil, afterDelay: 0.1)
        }get{
            return Int(_maxTime)
        }
    }
    
    override func draw(_ rect: CGRect) {
        let context: CGContext = UIGraphicsGetCurrentContext()!
        let center = CGPoint(x: self.frame.size.width / 2.0, y: self.frame.size.width/2.0)
        let radiud: CGFloat = CGFloat(self.frame.size.width / 2.0 - 5)
        let start_A: CGFloat = CGFloat(-(Double.pi / 2))
        let end_A: CGFloat = CGFloat(-(Double.pi / 2) + Double.pi * 2 * Double(progressValue))
        let path: UIBezierPath = UIBezierPath.init(arcCenter: center, radius: radiud, startAngle: start_A, endAngle: end_A, clockwise: true)
        
        context.setLineWidth(4)
        #colorLiteral(red: 1, green: 0.4613166451, blue: 0.3091258407, alpha: 1).setStroke()
        context.addPath(path.cgPath)
        context.strokePath()
    }
    
    /// 清除进度条
    func clearProgress(){
        currentTime = _maxTime
        self.isHidden = true
        progressValue = 0
        self.setNeedsDisplay()
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
    
    /// 开启进度条
    @objc func starProgress() {
        currentTime += 0.1
        if _maxTime > currentTime {
            progressValue = currentTime / _maxTime
        }
        print("\(progressValue)")
        self.setNeedsDisplay()
        if timer == nil {
            timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(starProgress), userInfo: nil, repeats: true)
        }
        if _maxTime <= currentTime{
            self.clearProgress()
        }
    }
}
